package control;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.board.BoardService;
import model.board.BoardVO;
import model.member.MemberVO;
import model.util.ListVO;
import model.util.ReplyVO;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class BoardController extends MultiActionController {
	
	private BoardService boardService;	
	
	private String thumbPath;
	private String imgpath;
	
	
	public BoardController(BoardService boardService,String thumbPath,String imgpath) {
		super();
		this.boardService = boardService;
		this.thumbPath=thumbPath;
		this.imgpath=imgpath;
	}



	public ModelAndView write(HttpServletRequest request,HttpServletResponse response,BoardVO vo){
		ModelAndView mv = new ModelAndView();
		String path = "redirect:index.jsp";
		try {
			HttpSession session = request.getSession(false);
			if(session != null && session.getAttribute("mvo")!=null){
				MemberVO memberVO = (MemberVO) session.getAttribute("mvo");
				vo.setMemberVO(memberVO);
				
				vo.setContents(vo.getContents().replace("\r\n","<br>"));
				
				MultipartFile mfile=vo.getUploadFile();
				if(mfile.isEmpty()==false){
					String fileName=mfile.getOriginalFilename();				
					vo.setOrgfilename(fileName);
					// 시간_파일명으로 저장 
					String newfilename=System.currentTimeMillis()+"_"+fileName;
					vo.setNewfilename(newfilename);
					File copyFile=new File(imgpath+newfilename);
					// 업로드..
					try {
						mfile.transferTo(copyFile);
					} catch (IllegalStateException e) {
						System.out.println(e.getMessage());
					} catch (IOException e) {
						System.out.println(e.getMessage());
					}
				}
				
			// -- 공지사항인지 구분한다. --
				String notice = request.getParameter("notice");
				if(notice.equals("notice")){
					vo.setCategory("notice_"+vo.getCategory());
					boardService.write(vo);
				}else if (notice.equals("nomal")){
					boardService.write(vo);
				}
			// -- 공지 추가 끝 --	
				path = "redirect:board.do?mode=content&no="+vo.getNo();
				
			}
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
		//System.out.println("디비 실행 후 : "+vo);
		
		mv.setViewName(path);
		return mv;
	}
	
	public ModelAndView content(HttpServletRequest request,HttpServletResponse response){
		
		HashMap map = new HashMap();
		BoardVO bvo = null;
		try {
			String no = request.getParameter("no");
			System.out.println("콘텐츠"+no);
			int cno = Integer.parseInt(no);
			bvo = boardService.content(cno);
			List list = boardService.reply_view(cno);
			map.put("list", list);
			map.put("bvo", bvo);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		System.out.println(bvo);
		return new ModelAndView("content.board","cvo",map);		
	}
	
	public ModelAndView list(HttpServletRequest request,HttpServletResponse response) throws SQLException{
		String category = request.getParameter("category");
		String pageNo = request.getParameter("page");
		ListVO lvo = boardService.getBoardList(category,pageNo);
		
		return new ModelAndView("list.board","bvo",lvo);
	}
	
	public ModelAndView view(HttpServletRequest request,HttpServletResponse response) throws SQLException{
		String write = request.getParameter("page");
		String path ="index";
		HttpSession session = request.getSession(false);
		if(session!=null && session.getAttribute("mvo")!=null){
			path = write+".board";
			//System.out.println("session 있음");
		}
		return new ModelAndView(path);
	}
	
	public ModelAndView updateView(HttpServletRequest request,HttpServletResponse response,BoardVO vo) throws SQLException{
		BoardVO bvo = null;
		bvo = boardService.content(vo.getNo());
		
		return new ModelAndView("update.board","bvo",bvo);	
			
	}
	
	public ModelAndView update(HttpServletRequest request,HttpServletResponse response,BoardVO vo) throws SQLException{
		ModelAndView mv = new ModelAndView(); 
		boardService.update(vo);
		String path = "redirect:board.do?mode=content&no="+vo.getNo();
		mv.setViewName(path);
		return mv;	
			
	}
	
	public ModelAndView delete(HttpServletRequest request,HttpServletResponse response,BoardVO vo) throws SQLException{
		String pageNo = request.getParameter("pageNo");
		boardService.delete(vo.getNo());
		
		return new ModelAndView("list.board","bvo",boardService.getBoardList(vo.getCategory(), pageNo));
	}
	
	
	public ModelAndView thumbImg(HttpServletRequest request,HttpServletResponse response,BoardVO vo) throws Exception{
		String dimg = request.getParameter("thumDel");
		MultipartFile mfile=vo.getUploadFile();
		String newfilename ="";
		if(mfile.isEmpty()==false){
			String fileName=mfile.getOriginalFilename();				
			vo.setOrgfilename(fileName);
			// 시간_파일명으로 저장 
			newfilename=System.currentTimeMillis()+"_"+fileName;
			vo.setNewfilename(newfilename);
			
			File copyFile=new File(thumbPath+newfilename);
			// 업로드..
			try {
				mfile.transferTo(copyFile);
				if(!dimg.equals("undefined")){
					boardService.deleteImg(thumbPath+dimg);
				}
			} catch (IllegalStateException e) {
				System.out.println(e.getMessage());
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
		
		
		//System.out.println(thumbPath);
		return new ModelAndView("JsonView","img",newfilename);
	}
	
	public ModelAndView reply_write(HttpServletRequest request,HttpServletResponse response) throws SQLException{
		
		String no = request.getParameter("board_no");
		int board_no = Integer.parseInt(no);
		String m_uid = request.getParameter("m_uid");
		String content = request.getParameter("content");
		String re = request.getParameter("restep");
		int restep = 0;
		if(re.equals("undefined")){
			restep=0;
		}else if(restep>=0){
			restep=boardService.getRestep(board_no)+1;
		}
		boardService.reply_write(board_no,m_uid,content,restep);
		
		List list = boardService.reply_view(board_no);
		return new ModelAndView("JsonView","list",list);
	}
	
	public ModelAndView reply_delete (HttpServletRequest request,HttpServletResponse response,ReplyVO vo) throws SQLException{
		ModelAndView mv = new ModelAndView();
		
		boardService.reply_delte(vo);
		String path = "redirect:board.do?mode=content&no="+vo.getRef();
		mv.setViewName(path);
		return mv;	
	}
	
	public ModelAndView findTitle(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String title = request.getParameter("title");
		String category = request.getParameter("category");
		String pageNo = "1";
		
		
		ListVO lvo = (ListVO) boardService.findTitle(title, category, pageNo);
		
		return new ModelAndView("list.board","bvo",lvo);
	}

}
